package br.com.jk.usuario;

import br.com.jk.master.Master;
import br.com.jk.usuario.jtable.UsuarioJTableUtil;
import br.com.jk.usuario.permissoes.Permissao;
import br.com.jk.usuario.permissoes.Permissao.Grupo;
import br.com.jk.usuario.permissoes.Permissao.Tipo;
import br.com.jk.usuario.permissoes.PermissaoTableModel;
import br.com.jk.util.StatusType.StatusUsuario;
import br.com.jk.util.Util;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 *
 * @author camilo
 */
public class UsuarioJDialog extends javax.swing.JDialog {

  private static UsuarioJDialog dialog;
  private static final long serialVersionUID = 1L;
  // Model da tabela
  UsuarioTableModel usuarioTm = new UsuarioTableModel();
  PermissaoTableModel permissaoTm = new PermissaoTableModel();
  UsuarioController control = new UsuarioController();
//  atributos utilizados nas pesquisas externas
  private JTextField idPesquisa;
  private JTextField razaoPesquisa;
  private boolean modoConsultaExt;
  private Integer id;
  private List<Integer> colunasComFiltro = new ArrayList<>();
  private Integer colunaSelecionada;

  public static UsuarioJDialog getInstance(java.awt.Frame parent, boolean modal) {
    if (dialog == null) {
      dialog = new UsuarioJDialog(parent, modal);
    }
    return dialog;
  }

  public static UsuarioJDialog getInstance(java.awt.Frame parent, boolean modal, JTextField id, JTextField razao) {
    if (dialog == null) {
      dialog = new UsuarioJDialog(parent, modal, id, razao);
    }
    return dialog;
  }

  /**
   * Creates new form FornecedorJDialog
   */
  private UsuarioJDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    init();
  }

  private UsuarioJDialog(java.awt.Frame parent, boolean modal, JTextField id, JTextField razao) {
    super(parent, modal);
    this.idPesquisa = id;
    this.razaoPesquisa = razao;
    this.modoConsultaExt = true;

    initComponents();
    init();
  }

  private void init() {
    criaModel();

    setLocationRelativeTo(null);
    listar();
    jlFiltro.setVisible(false);
    preencherJCombo();
  }

  private void criaModel() {
    jtUsuario.setModel(usuarioTm);

    jtPermissao.setModel(permissaoTm);
    jtPermissao.getTableHeader().setReorderingAllowed(false);

    usuarioTm.sorter(jtUsuario, usuarioTm);
    permissaoTm.sorter(jtPermissao, permissaoTm);

    jtfPesquisa.getDocument().addDocumentListener(new DocumentListener() {
      @Override
      public void insertUpdate(DocumentEvent de) {
        jbRefresh.setEnabled(false);
        usuarioTm.newFilter(jtfPesquisa, colunaSelecionada);
      }

      @Override
      public void removeUpdate(DocumentEvent de) {
        if (jtfPesquisa.getText().isEmpty()) {
          jbRefresh.setEnabled(true);
        }
        usuarioTm.newFilter(jtfPesquisa, colunaSelecionada);
      }

      @Override
      public void changedUpdate(DocumentEvent de) {
        usuarioTm.newFilter(jtfPesquisa, colunaSelecionada);
      }
    });

    UsuarioJTableUtil.alteraJTable(usuarioTm, jtUsuario, "jtUsuario", Master.usuarioLogado);
    UsuarioJTableUtil.alteraJTable(permissaoTm, jtPermissao, "jtPermissao", Master.usuarioLogado);
  }

  public void preencherJCombo() {
    jcbGrupo.removeAllItems();
    jcbTipo.removeAllItems();
    for (Tipo tipo : Tipo.values()) {
      jcbTipo.addItem(tipo);
    }
    for (Grupo grupo : Grupo.values()) {
      jcbGrupo.addItem(grupo);
    }
  }

  /**
   * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
   * content of this method is always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;

    JtbMaster = new javax.swing.JToolBar();
    JbNovo = new javax.swing.JButton();
    JbSalvar = new javax.swing.JButton();
    JbEditar = new javax.swing.JButton();
    JbCancelar = new javax.swing.JButton();
    JbExcluir = new javax.swing.JButton();
    jbBuscar = new javax.swing.JButton();
    JbRelatorio = new javax.swing.JButton();
    jSeparator1 = new javax.swing.JToolBar.Separator();
    jbRefresh = new javax.swing.JButton();
    jlFiltro = new javax.swing.JLabel();
    jSeparator2 = new javax.swing.JToolBar.Separator();
    jbJTable = new javax.swing.JButton();
    jspMaster = new javax.swing.JSplitPane();
    jspDados = new javax.swing.JSplitPane();
    jpDados = new javax.swing.JPanel();
    jLabel2 = new javax.swing.JLabel();
    jtfCod = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    jtfNome = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jtfNomeCompleto = new javax.swing.JTextField();
    jLabel4 = new javax.swing.JLabel();
    jtfDataCad = new javax.swing.JTextField();
    jLabel5 = new javax.swing.JLabel();
    jtfEmail = new javax.swing.JTextField();
    jLabel7 = new javax.swing.JLabel();
    jtfDataAlt = new javax.swing.JTextField();
    jcbxAtivo = new javax.swing.JCheckBox();
    jpJTable = new javax.swing.JPanel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jtUsuario = new javax.swing.JTable();
    jtfPesquisa = new javax.swing.JTextField();
    jpPermissao = new javax.swing.JPanel();
    jPanel1 = new javax.swing.JPanel();
    jcbTipo = new javax.swing.JComboBox();
    jcbGrupo = new javax.swing.JComboBox();
    jPanel2 = new javax.swing.JPanel();
    jScrollPane2 = new javax.swing.JScrollPane();
    jtPermissao = new javax.swing.JTable();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Cadastro de Usuários");
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosed(java.awt.event.WindowEvent evt) {
        formWindowClosed(evt);
      }
    });

    JtbMaster.setRollover(true);

    JbNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-new.png"))); // NOI18N
    JbNovo.setToolTipText("Novo Registro");
    JbNovo.setFocusable(false);
    JbNovo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbNovo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbNovo.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbNovoActionPerformed(evt);
      }
    });
    JtbMaster.add(JbNovo);

    JbSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-save-hd.png"))); // NOI18N
    JbSalvar.setToolTipText("Salvar Registro");
    JbSalvar.setEnabled(false);
    JbSalvar.setFocusable(false);
    JbSalvar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbSalvar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbSalvar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbSalvarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbSalvar);

    JbEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-edit.png"))); // NOI18N
    JbEditar.setToolTipText("Alterar registro");
    JbEditar.setEnabled(false);
    JbEditar.setFocusable(false);
    JbEditar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbEditar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbEditar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbEditarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbEditar);

    JbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/dialog-cancel.png"))); // NOI18N
    JbCancelar.setToolTipText("Cancelar");
    JbCancelar.setEnabled(false);
    JbCancelar.setFocusable(false);
    JbCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbCancelar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbCancelarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbCancelar);

    JbExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/archive-remove.png"))); // NOI18N
    JbExcluir.setToolTipText("Excluir");
    JbExcluir.setEnabled(false);
    JbExcluir.setFocusable(false);
    JbExcluir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbExcluir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbExcluir.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbExcluirActionPerformed(evt);
      }
    });
    JtbMaster.add(JbExcluir);

    jbBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/edit-find.png"))); // NOI18N
    jbBuscar.setToolTipText("Buscar");
    jbBuscar.setEnabled(false);
    jbBuscar.setFocusable(false);
    jbBuscar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jbBuscar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jbBuscar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbBuscarActionPerformed(evt);
      }
    });
    JtbMaster.add(jbBuscar);

    JbRelatorio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/report.png"))); // NOI18N
    JbRelatorio.setToolTipText("Relatórios");
    JbRelatorio.setEnabled(false);
    JbRelatorio.setFocusable(false);
    JbRelatorio.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRelatorio.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRelatorio.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRelatorioActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRelatorio);
    JtbMaster.add(jSeparator1);

    jbRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/view-refresh.png"))); // NOI18N
    jbRefresh.setToolTipText("Atualizar registros da lista");
    jbRefresh.setFocusable(false);
    jbRefresh.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jbRefresh.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jbRefresh.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbRefreshActionPerformed(evt);
      }
    });
    JtbMaster.add(jbRefresh);

    jlFiltro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/task-attempt.png"))); // NOI18N
    JtbMaster.add(jlFiltro);
    JtbMaster.add(jSeparator2);

    jbJTable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/view-form-table.png"))); // NOI18N
    jbJTable.setToolTipText("Grava as informações da JTable");
    jbJTable.setFocusable(false);
    jbJTable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jbJTable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jbJTable.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbJTableActionPerformed(evt);
      }
    });
    JtbMaster.add(jbJTable);

    jspMaster.setDividerLocation(350);
    jspMaster.setOneTouchExpandable(true);

    jspDados.setDividerLocation(300);
    jspDados.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
    jspDados.setOneTouchExpandable(true);

    jpDados.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(""), "Dados"));
    java.awt.GridBagLayout jpDadosLayout = new java.awt.GridBagLayout();
    jpDadosLayout.columnWidths = new int[] {100, 10, 110, 10, 110};
    jpDadosLayout.columnWeights = new double[] {0.0};
    jpDados.setLayout(jpDadosLayout);

    jLabel2.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel2.setText("Cod");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel2, gridBagConstraints);

    jtfCod.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfCod.setEnabled(false);
    jtfCod.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfCodKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfCod, gridBagConstraints);

    jLabel1.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel1.setText("Nome");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel1, gridBagConstraints);

    jtfNome.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfNome.setEnabled(false);
    jtfNome.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfNomeKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.gridwidth = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfNome, gridBagConstraints);

    jLabel3.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel3.setText("Nome Completo");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel3, gridBagConstraints);

    jtfNomeCompleto.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfNomeCompleto.setEnabled(false);
    jtfNomeCompleto.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfNomeCompletoKeyPressed(evt);
      }
      public void keyReleased(java.awt.event.KeyEvent evt) {
        jtfNomeCompletoKeyReleased(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.gridwidth = 5;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfNomeCompleto, gridBagConstraints);

    jLabel4.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel4.setText("Data Cad.");
    jLabel4.setToolTipText("Data Cadastro");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 6;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel4, gridBagConstraints);

    jtfDataCad.setEditable(false);
    jtfDataCad.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfDataCad.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 7;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfDataCad, gridBagConstraints);

    jLabel5.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel5.setText("Email");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 4;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel5, gridBagConstraints);

    jtfEmail.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfEmail.setEnabled(false);
    jtfEmail.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfEmailKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 5;
    gridBagConstraints.gridwidth = 5;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfEmail, gridBagConstraints);

    jLabel7.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel7.setText("Data Alt.");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 6;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel7, gridBagConstraints);

    jtfDataAlt.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfDataAlt.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 7;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfDataAlt, gridBagConstraints);

    jcbxAtivo.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jcbxAtivo.setText("Ativo");
    jcbxAtivo.setEnabled(false);
    jcbxAtivo.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jcbxAtivoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 7;
    jpDados.add(jcbxAtivo, gridBagConstraints);

    jspDados.setRightComponent(jpDados);

    jpJTable.setLayout(new java.awt.BorderLayout());

    jtUsuario.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
    jtUsuario.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        jtUsuarioMouseClicked(evt);
      }
    });
    jtUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyTyped(java.awt.event.KeyEvent evt) {
        jtUsuarioKeyTyped(evt);
      }
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtUsuarioKeyPressed(evt);
      }
    });
    jScrollPane1.setViewportView(jtUsuario);

    jpJTable.add(jScrollPane1, java.awt.BorderLayout.CENTER);

    jtfPesquisa.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfPesquisa.setToolTipText("Digite o conteúdo da pesquisa");
    jtfPesquisa.setEnabled(false);
    jtfPesquisa.setName(""); // NOI18N
    jpJTable.add(jtfPesquisa, java.awt.BorderLayout.PAGE_END);

    jspDados.setTopComponent(jpJTable);

    jspMaster.setLeftComponent(jspDados);

    jpPermissao.setBorder(javax.swing.BorderFactory.createEtchedBorder());

    jcbTipo.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N

    jcbGrupo.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jcbTipo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addComponent(jcbGrupo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    jPanel1Layout.setVerticalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel1Layout.createSequentialGroup()
        .addComponent(jcbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jcbGrupo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    );

    jPanel2.setLayout(new java.awt.BorderLayout());

    jScrollPane2.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N

    jtPermissao.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtPermissao.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
    jtPermissao.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mousePressed(java.awt.event.MouseEvent evt) {
        jtPermissaoMousePressed(evt);
      }
      public void mouseReleased(java.awt.event.MouseEvent evt) {
        jtPermissaoMouseReleased(evt);
      }
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        jtPermissaoMouseClicked(evt);
      }
    });
    jtPermissao.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtPermissaoKeyPressed(evt);
      }
    });
    jScrollPane2.setViewportView(jtPermissao);

    jPanel2.add(jScrollPane2, java.awt.BorderLayout.CENTER);

    javax.swing.GroupLayout jpPermissaoLayout = new javax.swing.GroupLayout(jpPermissao);
    jpPermissao.setLayout(jpPermissaoLayout);
    jpPermissaoLayout.setHorizontalGroup(
      jpPermissaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 419, Short.MAX_VALUE)
    );
    jpPermissaoLayout.setVerticalGroup(
      jpPermissaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jpPermissaoLayout.createSequentialGroup()
        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE))
    );

    jspMaster.setRightComponent(jpPermissao);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(JtbMaster, javax.swing.GroupLayout.DEFAULT_SIZE, 791, Short.MAX_VALUE)
      .addGroup(layout.createSequentialGroup()
        .addComponent(jspMaster, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
        .addContainerGap())
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(JtbMaster, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jspMaster, javax.swing.GroupLayout.DEFAULT_SIZE, 507, Short.MAX_VALUE))
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void JbNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbNovoActionPerformed
    novo();
  }//GEN-LAST:event_JbNovoActionPerformed

  private void JbSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbSalvarActionPerformed
    salvar();
  }//GEN-LAST:event_JbSalvarActionPerformed

  private void JbEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbEditarActionPerformed
    editar();
  }//GEN-LAST:event_JbEditarActionPerformed

  private void JbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbCancelarActionPerformed
    cancelar();
  }//GEN-LAST:event_JbCancelarActionPerformed

  private void JbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbExcluirActionPerformed
    excluir();
  }//GEN-LAST:event_JbExcluirActionPerformed

  private void jbBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbBuscarActionPerformed
    pesquisar();
  }//GEN-LAST:event_jbBuscarActionPerformed

  private void JbRelatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRelatorioActionPerformed
    try {
//      Master.setJpbStatusIndeterminate(true);
//      Master.setTextJlStatus("Gerando relatório...");
      ThreadReport thReport = new ThreadReport();
      thReport.start();

    } catch (Exception e) {
      Util.msgErro(e, "Erro ao gerar o relatório");
    }
  }//GEN-LAST:event_JbRelatorioActionPerformed

  private void jbRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbRefreshActionPerformed
    listar();
    jlFiltro.setVisible(false);
    jbBuscar.setEnabled(false);
  }//GEN-LAST:event_jbRefreshActionPerformed

  private void jtUsuarioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtUsuarioMouseClicked
    if (usuarioTm.getRowCount() > 0 && (jtfCod.getText() != null && jtfNomeCompleto != null)) {
      habilitaJb(true, false, true, false, true);
      habilitaJtf(false);
      limpar();
      selecionado();
    }
  }//GEN-LAST:event_jtUsuarioMouseClicked

  private void jtfCodKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfCodKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfNome.requestFocus();
    }
  }//GEN-LAST:event_jtfCodKeyPressed

  private void jtfNomeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfNomeKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfNomeCompleto.requestFocus();
    }
  }//GEN-LAST:event_jtfNomeKeyPressed

  private void jtfNomeCompletoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfNomeCompletoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfEmail.requestFocus();
    }
  }//GEN-LAST:event_jtfNomeCompletoKeyPressed

  private void jtfEmailKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfEmailKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jcbxAtivo.requestFocus();
    }
  }//GEN-LAST:event_jtfEmailKeyPressed

  private void jtUsuarioKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtUsuarioKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
      if (jbBuscar.isEnabled()) {
        control.pesquisar();
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (modoConsultaExt) {
        selecionaRegistro();
      }
    }
  }//GEN-LAST:event_jtUsuarioKeyPressed

  private void jtfNomeCompletoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfNomeCompletoKeyReleased
    Util.setFirstLetterUpperCase(jtfNomeCompleto, jtfNomeCompleto.getSelectionStart());
  }//GEN-LAST:event_jtfNomeCompletoKeyReleased

  private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    dialog = null;
  }//GEN-LAST:event_formWindowClosed

  private void jcbxAtivoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jcbxAtivoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      salvar();
    }
  }//GEN-LAST:event_jcbxAtivoKeyPressed

  private void jbJTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbJTableActionPerformed
    getLarguraJtBanco();
  }//GEN-LAST:event_jbJTableActionPerformed

  private void jtUsuarioKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtUsuarioKeyTyped
    if (evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN
            || evt.getKeyCode() == KeyEvent.VK_LEFT || evt.getKeyCode() == KeyEvent.VK_RIGHT) {
      selecionado();
    }
  }//GEN-LAST:event_jtUsuarioKeyTyped

  private void jtPermissaoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtPermissaoMouseClicked
  }//GEN-LAST:event_jtPermissaoMouseClicked

  private void jtPermissaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtPermissaoKeyPressed
  }//GEN-LAST:event_jtPermissaoKeyPressed

  private void jtPermissaoMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtPermissaoMouseReleased
  }//GEN-LAST:event_jtPermissaoMouseReleased

  private void jtPermissaoMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtPermissaoMousePressed
    if (jtPermissao.getSelectedColumn() == PermissaoTableModel.COLUNA_COD_HABILITADO) {
      alteraPermissao();
    }

  }//GEN-LAST:event_jtPermissaoMousePressed

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(UsuarioJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(UsuarioJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(UsuarioJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(UsuarioJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        UsuarioJDialog dialog = new UsuarioJDialog(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
          @Override
          public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
          }
        });
        dialog.setVisible(true);
      }
    });
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton JbCancelar;
  private javax.swing.JButton JbEditar;
  private javax.swing.JButton JbExcluir;
  private javax.swing.JButton JbNovo;
  private javax.swing.JButton JbRelatorio;
  private javax.swing.JButton JbSalvar;
  private javax.swing.JToolBar JtbMaster;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JLabel jLabel5;
  private javax.swing.JLabel jLabel7;
  private javax.swing.JPanel jPanel1;
  private javax.swing.JPanel jPanel2;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JScrollPane jScrollPane2;
  private javax.swing.JToolBar.Separator jSeparator1;
  private javax.swing.JToolBar.Separator jSeparator2;
  private javax.swing.JButton jbBuscar;
  private javax.swing.JButton jbJTable;
  private javax.swing.JButton jbRefresh;
  private javax.swing.JComboBox jcbGrupo;
  private javax.swing.JComboBox jcbTipo;
  private javax.swing.JCheckBox jcbxAtivo;
  private javax.swing.JLabel jlFiltro;
  private javax.swing.JPanel jpDados;
  private javax.swing.JPanel jpJTable;
  private javax.swing.JPanel jpPermissao;
  private javax.swing.JSplitPane jspDados;
  private javax.swing.JSplitPane jspMaster;
  private javax.swing.JTable jtPermissao;
  private javax.swing.JTable jtUsuario;
  private javax.swing.JTextField jtfCod;
  private javax.swing.JTextField jtfDataAlt;
  private javax.swing.JTextField jtfDataCad;
  private javax.swing.JTextField jtfEmail;
  private javax.swing.JTextField jtfNome;
  private javax.swing.JTextField jtfNomeCompleto;
  private javax.swing.JTextField jtfPesquisa;
  // End of variables declaration//GEN-END:variables
  Util.ValidaDigitacaoData docDataCadastro = new Util().new ValidaDigitacaoData();

  public void novo() {
    limpar();
    habilitaJb(false, true, false, true, false);
    habilitaJtf(true);

    jtfDataCad.setText(Util.formatData(new Date(System.currentTimeMillis())));

    jtfCod.setEnabled(true);
    jtfCod.requestFocus();
  }

  private void getLarguraJtBanco() {
    UsuarioJTableUtil.setUsuarioJTable(usuarioTm, jtUsuario, "jtUsuario", Master.usuarioLogado);
    UsuarioJTableUtil.setUsuarioJTable(permissaoTm, jtPermissao, "jtPermissao", Master.usuarioLogado);
  }

  public void selecionado() {
    int linha = jtUsuario.getSelectedRow();//grava a linha selecionada
    int linhaSel = jtUsuario.convertRowIndexToModel(linha);

    if (linhaSel >= 0) { // executa o procedimento se o JTable não estiver vazio
      int colunaSel = jtUsuario.getSelectedColumn(); //grava a coluna selecionada
      colunaSelecionada = colunaSel;

      boolean pesq = control.setEnabledPesquisa(jtUsuario.convertColumnIndexToModel(colunaSel)); // Verifica as colunas que serão habilitadas para pesquisa

      id = Integer.parseInt(usuarioTm.getValueAt(linhaSel, UsuarioTableModel.COLUNA_COD_ID).toString());
      jtfCod.setText(usuarioTm.getValueAt(linhaSel, UsuarioTableModel.COLUNA_COD_COD).toString());
      jtfDataCad.setText(Util.formatDataStoS(usuarioTm.getValueAt(linhaSel, UsuarioTableModel.COLUNA_COD_DATA_CADASTRO).toString()));
      jtfNome.setText(usuarioTm.getValueAt(linhaSel, UsuarioTableModel.COLUNA_COD_NOME).toString());
      jtfNomeCompleto.setText(usuarioTm.getValueAt(linhaSel, UsuarioTableModel.COLUNA_COD_NOME_COMPLETO).toString());
      try {
        jtfDataAlt.setText(Util.formatDataStoS(usuarioTm.getValueAt(linhaSel, UsuarioTableModel.COLUNA_COD_DATA_ALTERACAO).toString()));
      } catch (NullPointerException e) {
        jtfDataAlt.setText("");
      }
      jtfEmail.setText(usuarioTm.getValueAt(linhaSel, UsuarioTableModel.COLUNA_COD_EMAIL).toString());

      String status = usuarioTm.getValueAt(linhaSel, UsuarioTableModel.COLUNA_COD_STATUS).toString();
      if (StatusUsuario.valueOf(status) == StatusUsuario.ATIVO) {
        jcbxAtivo.setSelected(true);
      } else {
        jcbxAtivo.setSelected(false);
      }

      control.modoConsulta = pesq;
      jtfPesquisa.setEnabled(pesq);
      setJtPermissaoTm(control.listarPermissoes(criaObjeto()));
    }
  }

  public Usuario criaObjeto() {
    Usuario usuario = new Usuario();
    if (jcbxAtivo.isSelected()) {
      usuario.setStatus(StatusUsuario.ATIVO);
    } else {
      usuario.setStatus(StatusUsuario.INATIVO);
    }

    usuario.setDataCadastro(Util.formatDataSToD(jtfDataCad.getText()));
    usuario.setCod(jtfCod.getText());
    if (!jtfDataAlt.getText().isEmpty()) {
      usuario.setDataAlteração(Util.formatDataSToD(jtfDataAlt.getText()));
    }
    usuario.setEmail(jtfEmail.getText());
    usuario.setNome(jtfNome.getText());
    usuario.setNomeCompleto(jtfNomeCompleto.getText());

    if (id != null) {
      usuario.setId(id);
    }

    return usuario;
  }

  private void salvar() {
    control.salvar(criaObjeto());
    listar();
    habilitaJb(true, false, false, false, false);
    habilitaJtf(false);
    jtfCod.setEnabled(false);
    limpar();
  }

  private void listar() {
    colunasComFiltro.clear();
    setJtUsuarioTm(control.listar());

    limpar();
  }

  private void limpar() {
    id = null;
    jtfNome.setText(null);
    jtfNomeCompleto.setText(null);
    jtfDataCad.setText(null);
    jtfCod.setText(null);
    jtfDataAlt.setText(null);
    jtfEmail.setText(null);
    jcbxAtivo.setSelected(false);
    jbBuscar.setEnabled(false);
  }

  public void setJtPermissaoTm(List<Permissao> ct) {
    removeAllJtablePermissao();
    if (!ct.isEmpty()) {
      permissaoTm.adicionaLista(ct);
    }
  }

  public void setJtUsuarioTm(List<Usuario> ct) {
    removeAllJtableUsuario();
    if (!ct.isEmpty()) {
      usuarioTm.adicionaLista(ct);
    }
  }

  public void setJtUsuarioTm(Usuario ct) {
    removeAllJtableUsuario();
    if (ct != null) {
      usuarioTm.adiciona(ct);
    }
  }

  private void removeAllJtablePermissao() {
//    usuarioTm.removeAll();
    while (permissaoTm.getRowCount() > 0) {
      permissaoTm.remove(0);
    }
  }

  private void removeAllJtableUsuario() {
//    usuarioTm.removeAll();
    while (usuarioTm.getRowCount() > 0) {
      usuarioTm.remove(0);
    }
  }

  /**
   * Determina quais os botões da barra de ferramentas ficará ativo
   *
   * @param novo
   * @param salvar
   * @param editar
   * @param cancelar
   * @param excluir
   */
  public void habilitaJb(Boolean novo, Boolean salvar, Boolean editar, Boolean cancelar,
          Boolean excluir) {
    JbNovo.setEnabled(novo);
    JbSalvar.setEnabled(salvar);
    JbEditar.setEnabled(editar);
    JbCancelar.setEnabled(cancelar);
    JbExcluir.setEnabled(excluir);
  }

  /**
   * Define se os JTextFields serão liberados para edição do usuário
   *
   * @param tf <b>True</b> - Habilitar; <b>False</b> - Desabilitar;
   */
  public void habilitaJtf(Boolean tf) {
    jtfNome.setEnabled(tf);
    jtfNomeCompleto.setEnabled(tf);
    jtfEmail.setEnabled(tf);
    jcbxAtivo.setEnabled(tf);
    if (tf) {
      jspDados.setDividerLocation(300);
    }
  }

  private void editar() {
    habilitaJb(false, true, false, true, false);
    habilitaJtf(true);
    jtfDataCad.requestFocus();
  }

  private void excluir() {
    control.excluir(criaObjeto());
    listar();
    limpar();
  }

  private void cancelar() {
    limpar();
    habilitaJb(true, false, false, false, false);
    habilitaJtf(false);
    jtfCod.setEnabled(false);
    if (control.modoConsulta) {
      control.modoConsulta = false;
    } else {
      listar();
    }
  }

  private void selecionaRegistro() {
    int linha = jtUsuario.getSelectedRow();
    int linhaSel = jtUsuario.convertRowIndexToModel(linha);
    idPesquisa.setText(usuarioTm.getValueAt(linhaSel, UsuarioTableModel.COLUNA_COD_ID).toString());
    razaoPesquisa.setText(usuarioTm.getValueAt(linhaSel, UsuarioTableModel.COLUNA_COD_NOME_COMPLETO).toString());
    modoConsultaExt = false;
    this.dispose();
  }

  private void pesquisar() {
    if (control.modoConsulta) {
      Integer colSel = jtUsuario.getSelectedColumn();
      System.out.println("coluna antes de converter: " + colSel);
//      colunaSelecionada = jtUsuario.convertRowIndexToModel(colunaSelecionada);
//      System.out.println("coluna após converter: " + colunaSelecionada);

      usuarioTm.newFilter(jtfPesquisa, colSel);

      colunasComFiltro.add(colSel);
      System.out.println(colSel);
    }
  }
  
  private void alteraPermissao(){
    int linhaSelecionada = jtPermissao.convertRowIndexToModel(jtPermissao.getSelectedRow());
    int idSelecao = Integer.parseInt(permissaoTm.getValueAt(linhaSelecionada, PermissaoTableModel.COLUNA_COD_ID).toString());
    Boolean habilitado = Boolean.parseBoolean(permissaoTm.getValueAt(linhaSelecionada, PermissaoTableModel.COLUNA_COD_HABILITADO).toString());
    
    control.alteraPermissao(idSelecao, !habilitado);
  }

  class ThreadReport extends Thread {

    @Override
    public void run() {
      try {
        control.report();
      } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage());
      }
    }
  }
}
